// app/src/main/java/com/example/hlddz2/viewmodel/HomeViewModel.java
package com.example.hlddz2.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.hlddz2.model.NavItem;
import com.example.hlddz2.model.NavItemResponse;
import com.example.hlddz2.model.Product;
import com.example.hlddz2.repository.ProductRepository;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;

public class HomeViewModel extends ViewModel {
    private static final String TAG = "HomeViewModel";
    private MutableLiveData<List<NavItem>> navItems = new MutableLiveData<>();
    private MutableLiveData<List<Product>> goodsList = new MutableLiveData<>();
    private CompositeDisposable disposable = new CompositeDisposable();

    private ProductRepository repository;

    public HomeViewModel(ProductRepository repository) {
        this.repository = repository;
    }

    public LiveData<List<NavItem>> getNavItems() {
        return navItems;
    }

    public LiveData<List<Product>> getGoodsList() {
        return goodsList;
    }

    public void loadNavItems() {
        disposable.add(repository.getNavItems()
                .subscribeWith(new DisposableObserver<NavItemResponse>() {
                    @Override
                    public void onNext(NavItemResponse response) {
                        navItems.setValue(response.getMessage());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "Error loading nav items", e);
                        navItems.setValue(null); // 或者设置一个空列表
                    }

                    @Override
                    public void onComplete() {}
                }));
    }

    public void loadGoodsList(String query, int cid, int pagesize, int pagenum) {
        // repository.getGoodsList 现在返回 Observable<List<Product>>
        disposable.add(repository.getGoodsList(query, cid, pagesize, pagenum)
                .subscribeWith(new DisposableObserver<List<Product>>() { // 注意这里接收的是 List<Product>

                    @Override
                    public void onNext(List<Product> responseProducts) {
                        goodsList.setValue(responseProducts);
                        Log.d(TAG, "成功加载 " + responseProducts.size() + " 个商品");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "Error loading goods list", e);
                        goodsList.setValue(new ArrayList<>()); // 出错时设置为空列表而不是null
                    }

                    @Override
                    public void onComplete() {}
                }));
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        disposable.clear();
    }
}